package com.husong.controller;

import static com.husong.enums.AuthodType.jincongmin;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.InputSource;

import com.husong.config.Config;
import com.husong.cons.ReturnCodeAndMsg;
import com.husong.controller.base.BaseController;
import com.husong.entity.AccountBind;
import com.husong.entity.BrokerDetail;
import com.husong.entity.Feedback;
import com.husong.entity.PayOrder;
import com.husong.entity.RechargeList;
import com.husong.entity.TrainPic;
import com.husong.entity.TrainTest;
import com.husong.entity.User;
import com.husong.entity.UserWallet;
import com.husong.pojo.AccountBindBean;
import com.husong.pojo.BillBean;
import com.husong.pojo.BillDetailBean;
import com.husong.pojo.ReturnJsonBean;
import com.husong.pojo.UserBean;
import com.husong.pojo.UserModel;
import com.husong.pojo.UserWalletBean;
import com.husong.pojo.WalletBean;
import com.husong.pojo.WithdrawOrderBean;
import com.husong.pojo.WxPayResult;
import com.husong.service.UserService;
import com.husong.util.BeanUtil;
import com.husong.util.CacheUtil;
import com.husong.util.LoggerUtils;
import com.husong.util.PayOrderNoUtil;
import com.husong.util.PointUtil;
import com.husong.util.UUIDUtil;
import com.husong.util.tenpay.util.Constants;
import com.husong.util.tenpay.util.MD5;
import com.husong.util.tenpay.util.MD5Util;
import com.husong.util.tenpay.util.TenpayUtil;
import com.husong.util.tenpay.util.Util;

/**
 * @author MaxMin.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {
	/**
	 * 发送注册验证码
	 *
	 * @param telephone
	 *
	 * @return
	 */
	@RequestMapping(value = "/regist/code", method = RequestMethod.POST)
	@ResponseBody
	public ReturnJsonBean registCode(String telephone) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			boolean isExsit = userService.checkUserIsExsit(telephone);
			if (isExsit) {
				returnFail(rb, ReturnCodeAndMsg.ACCOUNT_IS_EXSIST, ReturnCodeAndMsg.ACCOUNT_IS_EXSIST_MSG);
			} else {
				sendCode(telephone, Config.REGIST_VALICODE_EFFECTIVE_TIME);
				returnSuccess(rb);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "registCode()", e);
		}
		return rb;
	}

	/**
	 * 发送设置支付密码验证码
	 *
	 * @param telephone
	 *
	 * @return
	 */
	@RequestMapping(value = "/pay/code", method = RequestMethod.POST)
	@ResponseBody
	public ReturnJsonBean payCode(String telephone) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			boolean isExsit = userService.checkUserIsExsit(telephone);
			if (!isExsit) {
				returnFail(rb, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST_MSG);
			} else {
				sendCode(telephone, Config.REGIST_VALICODE_EFFECTIVE_TIME);
				returnSuccess(rb);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "payCode()", e);
		}
		return rb;
	}

	/**
	 * 用户注册接口
	 *
	 * @param telephone
	 *            手机号
	 * @param cityname
	 *            城市名
	 * @param code
	 *            验证码
	 *
	 * @return
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	@ResponseBody
	public ReturnJsonBean regist(String telephone, String cityname, String code, String inviteCode) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			boolean isExsit = userService.checkUserIsExsit(telephone);
			if (isExsit) {
				returnFail(rb, ReturnCodeAndMsg.ACCOUNT_IS_EXSIST, ReturnCodeAndMsg.ACCOUNT_IS_EXSIST_MSG);
				return rb;
			} else {
				CacheUtil cacheUtil = CacheUtil.getInstance();
				String cd = (String) cacheUtil.get(telephone);
				LoggerUtils.info(getClass().getName(), telephone + "缓存的验证码：" + cd);
				if (cd == null || "".equals(cd)) {
					returnFail(rb, ReturnCodeAndMsg.VALICODE_OVERDUE, ReturnCodeAndMsg.VALICODE_OVERDUE_MSG);
					return rb;
				}
				if (!"".equals(code) && code != null) {
					if (code.equalsIgnoreCase(cd)) {
						User user = userService.regist(telephone, cityname, code);
						if (user == null) {
							returnFail(rb, ReturnCodeAndMsg.ACCOUNT_REGIST_FAIL,
									ReturnCodeAndMsg.ACCOUNT_REGIST_FAIL_MSG);
							return rb;
						} else {
							user = userService.login(telephone);
							if (user != null) {
								// 如果登录成功,生成一个secret key 在缓存中记录
								String primaryKey = cacheLogin(user.getUserId());

								UserWalletBean wallet = userService.getUsefullUserWalletBeanByUserId(user.getUserId());
								if (wallet == null) {
									userService.addUserWallet(user.getUserId());
									wallet = userService.getUsefullUserWalletBeanByUserId(user.getUserId());
								}
								Integer isSetPayPassword = 0;
								if (wallet.getPay_password() == null || "".equals(wallet.getPay_password().trim())) {
									isSetPayPassword = 0;
								} else {
									isSetPayPassword = 1;
								}

								UserBean bean = null;
								if (user != null) {
									bean = BeanUtil.buildUserBean(user);
									bean.setIsSetPayPassword(isSetPayPassword);
									List<AccountBindBean> beans = userService.getAccountBinds(user.getUserId());
									if (beans != null && beans.size() > 0) {
										bean.setIsBindWithdrawAccount(1);
									} else {
										bean.setIsBindWithdrawAccount(0);
									}
								}
								bean.setKey(user.getUserId());
								bean.setPrimaryKey(getKey(user.getUserId()));
								rb.setData(bean);
								returnSuccess(rb);
								return rb;
							} else {
								returnFail(rb, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST,
										ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST_MSG);
								return rb;
							}

							//// Map<String, String> map = new HashMap<String,
							//// String>();
							//// map.put(Constants.PARAM_KEY, user.getUserId());
							//// rb.setData(map);
							// cacheLogin(user.getUserId());
						}

					}
				} else {
					returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
					return rb;
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "regist()", e);
		}
		return rb;
	}

	/**
	 * 使用验证码登录 ，发送验证码的请求。
	 *
	 * @param telephone
	 *            手机号
	 *
	 * @return
	 */
	@RequestMapping(value = "/login/code", method = RequestMethod.POST)
	@ResponseBody
	public ReturnJsonBean loginCode(String telephone) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.login(telephone);
			if (user != null) {
				sendCode(telephone, Config.LOGIN_VALICODE_EFFECTIVE_TIME_SECEND);
				// Map<String, User> map = new HashMap<String, User>();
				// user.setTitle(PointUtil.convertToTitle(user.getPoint()));
				// map.put("user", user);
				returnSuccess(rb);
			} else {
				returnFail(rb, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST_MSG);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "loginCode()", e);
		}
		return rb;
	}

	/**
	 * 用户登录接口
	 *
	 * @param telephone
	 * @param code
	 *
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public ReturnJsonBean login(String telephone, String code) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			CacheUtil cacheUtil = CacheUtil.getInstance();
			String cd = (String) cacheUtil.get(telephone);
			LoggerUtils.info(getClass().getName(), telephone + "缓存的验证码：" + cd);
			if (cd == null || "".equals(cd)) {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_OVERDUE, ReturnCodeAndMsg.VALICODE_OVERDUE_MSG);
				return rb;
			}
			if (!"".equals(code) && code != null) {
				if (code.equalsIgnoreCase(cd)) {
					User user = userService.login(telephone);
					if (user != null) {
						// 如果登录成功,生成一个secret key 在缓存中记录
						String primaryKey = cacheLogin(user.getUserId());

						UserWalletBean wallet = userService.getUsefullUserWalletBeanByUserId(user.getUserId());
						if (wallet == null) {
							userService.addUserWallet(user.getUserId());
							wallet = userService.getUsefullUserWalletBeanByUserId(user.getUserId());
						}
						Integer isSetPayPassword = 0;
						if (wallet.getPay_password() == null || "".equals(wallet.getPay_password().trim())) {
							isSetPayPassword = 0;
						} else {
							isSetPayPassword = 1;
						}

						UserBean bean = null;
						if (user != null) {
							bean = BeanUtil.buildUserBean(user);
							bean.setIsSetPayPassword(isSetPayPassword);
							List<AccountBindBean> beans = userService.getAccountBinds(user.getUserId());
							if (beans != null && beans.size() > 0) {
								bean.setIsBindWithdrawAccount(1);
							} else {
								bean.setIsBindWithdrawAccount(0);
							}
						}
						bean.setKey(user.getUserId());
						bean.setPrimaryKey(getKey(user.getUserId()));
						rb.setData(bean);
						returnSuccess(rb);
					} else {

						returnFail(rb, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST, ReturnCodeAndMsg.ACCOUNT_NOT_EXSIST_MSG);
					}
				} else {
					returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
				}
			} else {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_IS_EMPTY, ReturnCodeAndMsg.VALICODE_IS_EMPTY_MSG);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "login()", e);
		}
		if (rb.getData() == null || "".equals(rb.getData())) {
			rb.setData(null);
		}
		return rb;
	}

	/**
	 * 退出登录
	 *
	 * @param key
	 *            用户id
	 *
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@ResponseBody
	public ReturnJsonBean logout(String key) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			CacheUtil cacheUtil = CacheUtil.getInstance();
			cacheUtil.delete(key);
			rb.setCode(ReturnCodeAndMsg.SUCCESS);
			rb.setMessage(ReturnCodeAndMsg.SUCCESS_MSG);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "logout()", e);
		}
		return rb;
	}

	/**
	 * @author maxmin
	 * @date 2015/11/13
	 */
	@RequestMapping("/detail")
	@ResponseBody
	public ReturnJsonBean detail(String key) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.get(key);
			rb.setData(user);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "detail()", e);
		}
		return rb;
	}

	/**
	 * 获取培训内容
	 */
	@RequestMapping("/trainpic")
	@ResponseBody
	public ReturnJsonBean trainpic() {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			List<TrainPic> pics = userService.trainPics();
			rb.setData(pics);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "detail()", e);
		}
		return rb;
	}

	/**
	 * 获取考试题目
	 */
	@RequestMapping("/traintest")
	@ResponseBody
	public ReturnJsonBean traintest() {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			List<TrainTest> tests = userService.trainTests();
			rb.setData(tests);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "detail()", e);
		}
		return rb;
	}

	/**
	 * 完成培训
	 */
	@RequestMapping("/trainpic/finish")
	@ResponseBody
	public ReturnJsonBean trainpic_finish(String brokerid) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			userService.trained(brokerid);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "detail()", e);
		}
		return rb;
	}

	/**
	 * 完成考试
	 */
	@RequestMapping("/traintest/finish")
	@ResponseBody
	public ReturnJsonBean traintest_finish(String brokerid) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			userService.tested(brokerid);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "detail()", e);
		}
		return rb;
	}

	/**
	 * 经纪人认证
	 */
	@RequestMapping("/authen")
	@ResponseBody
	public ReturnJsonBean authen(User user) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			userService.authen(user);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "authen()", e);
		}
		return rb;
	}

	/**
	 * 查询钱包
	 */
	@RequestMapping("/wallet")
	@ResponseBody
	public ReturnJsonBean wallet(String user_id) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			UserWalletBean wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			if (wallet == null) {
				userService.addUserWallet(user_id);
				wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			}

			UserWallet userWallet = BeanUtil.buildUserWallet(wallet);
			rb.setData(userWallet);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "authen()", e);
		}
		return rb;
	}

	/**
	 * 设置钱包密码
	 */
	@RequestMapping("/wallet/password/set")
	@ResponseBody
	public ReturnJsonBean wallet_password_set(String user_id, String password) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			userService.updateWalletPassword(user_id, password);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "authen()", e);
		}
		return rb;
	}

	/**
	 * 修改钱包密码
	 */
	@RequestMapping("/wallet/password/update")
	@ResponseBody
	public ReturnJsonBean wallet_password_update(String user_id, String password, String code) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			// UserWalletBean
			// wallet=userService.getUsefullUserWalletBeanByUserId(user_id);
			User user = userService.get(user_id);
			CacheUtil cacheUtil = CacheUtil.getInstance();
			String cd = (String) cacheUtil.get(user.getTelephone());
			LoggerUtils.info(getClass().getName(), user.getTelephone() + "缓存的验证码：" + cd);
			if (cd == null || "".equals(cd)) {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_OVERDUE, ReturnCodeAndMsg.VALICODE_OVERDUE_MSG);
				return rb;
			}
			if (!"".equals(code) && code != null) {
				if (code.equalsIgnoreCase(cd)) {
					userService.updateWalletPassword(user_id, password);
					returnSuccess(rb);
				} else {
					returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
				}

			} else {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "wallet_password_update()", e);
		}
		return rb;
	}

	/**
	 * 绑定账号
	 */
	@RequestMapping("/withdraw/account/bind")
	@ResponseBody
	public ReturnJsonBean withdraw_account_bind(String user_id, String real_name, String account_no, String code,
			Integer account_type) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.get(user_id);
			CacheUtil cacheUtil = CacheUtil.getInstance();
			String cd = (String) cacheUtil.get(user.getTelephone());
			LoggerUtils.info(getClass().getName(), user.getTelephone() + "缓存的验证码：" + cd);
			if (cd == null || "".equals(cd)) {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_OVERDUE, ReturnCodeAndMsg.VALICODE_OVERDUE_MSG);
				return rb;
			}
			if (!"".equals(code) && code != null) {
				if (code.equalsIgnoreCase(cd)) {
					AccountBindBean bean = new AccountBindBean();
					bean.setAccount_no(account_no);
					bean.setAccount_type(account_type);
					bean.setBind_time(new Timestamp(System.currentTimeMillis()));
					bean.setId(UUIDUtil.getUUID());
					bean.setReal_name(real_name);
					bean.setUser_id(user_id);
					userService.addAccountBind(bean);
					returnSuccess(rb);
				}else{
					returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
				}
			} else {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "authen()", e);
		}
		return rb;
	}

	/**
	 * 修改绑定账号
	 */
	@RequestMapping("/withdraw/account/bind/update")
	@ResponseBody
	public ReturnJsonBean withdraw_account_bind_update(String bind_id, String user_id, String real_name,
			String account_no, String code, Integer account_type) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.get(user_id);
			CacheUtil cacheUtil = CacheUtil.getInstance();
			String cd = (String) cacheUtil.get(user.getTelephone());
			LoggerUtils.info(getClass().getName(), user.getTelephone() + "缓存的验证码：" + cd);
			if (!"".equals(code) && code != null) {
				if (code.equalsIgnoreCase(cd)) {
					AccountBindBean bean = new AccountBindBean();
					bean.setAccount_no(account_no);
					bean.setAccount_type(account_type);
					bean.setBind_time(new Timestamp(System.currentTimeMillis()));
					bean.setUpdate_time(new Timestamp(System.currentTimeMillis()));
					bean.setId(bind_id);
					bean.setReal_name(real_name);
					bean.setUser_id(user_id);
					userService.updateAccountBind(bean);
					returnSuccess(rb);
				}
			} else {
				returnFail(rb, ReturnCodeAndMsg.VALICODE_ERROR, ReturnCodeAndMsg.VALICODE_ERROR_MSG);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "authen()", e);
		}
		return rb;
	}

	/**
	 * 获取用户绑定的账号
	 */
	@RequestMapping("/withdraw/account/bind/get")
	@ResponseBody
	public ReturnJsonBean withdraw_account_bind_get(String user_id) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			List<AccountBindBean> beans = userService.getAccountBinds(user_id);
			List<AccountBind> binds = new ArrayList<AccountBind>();
			for (AccountBindBean bean : beans) {
				AccountBind bind = BeanUtil.buildAccountBind(bean);
				binds.add(bind);
			}
			rb.setData(binds);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "authen()", e);
		}
		return rb;
	}

	/**
	 * 查詢用戶信息
	 */
	@RequestMapping("/info")
	@ResponseBody
	public ReturnJsonBean info(String user_id) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.get(user_id);
			UserWalletBean wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			if (wallet == null) {
				userService.addUserWallet(user_id);
				wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			}
			Integer isSetPayPassword = 0;
			if (wallet.getPay_password() == null || "".equals(wallet.getPay_password().trim())) {
				isSetPayPassword = 0;
			} else {
				isSetPayPassword = 1;
			}

			UserBean bean = null;
			if (user != null) {
				bean = BeanUtil.buildUserBean(user);
				bean.setIsSetPayPassword(isSetPayPassword);
				List<AccountBindBean> beans = userService.getAccountBinds(user.getUserId());
				if (beans != null && beans.size() > 0) {
					bean.setIsBindWithdrawAccount(1);
				} else {
					bean.setIsBindWithdrawAccount(0);
				}
			}
			bean.setKey(user.getUserId());
			bean.setPrimaryKey(getKey(user_id));
			rb.setData(bean);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "info()", e);
		}
		return rb;
	}

	/**
	 * 查詢个人信息
	 */
	@RequestMapping("/person/info")
	@ResponseBody
	public ReturnJsonBean person_info(String user_id) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.get(user_id);
			BrokerDetail detail = new BrokerDetail();
			detail.setAge(getAgeByBirthday(user.getBirthday()));
			if (user.getDeclaration() == null || "".equals(user.getDeclaration())) {
				detail.setDeclaration("这个人很懒，什么都没有留下！");
			} else {
				detail.setDeclaration(user.getDeclaration());
			}
			detail.setPoint(user.getPoint());
			detail.setSex(user.getGender());
			detail.setStars(user.getStars());
			detail.setTitle(PointUtil.convertToTitle(user.getPoint()));
			detail.setUserId(user_id);
			detail.setUsername(user.getUsername());
			detail.setHeader(user.getHeader());
			rb.setData(detail);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "person_info()", e);
		}
		return rb;
	}

	public static int getAgeByBirthday(Date birthday) {
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthday)) {
			throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
		}

		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		cal.setTime(birthday);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				// monthNow==monthBirth
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				// monthNow>monthBirth
				age--;
			}
		}
		return age;
	}

	/**
	 * 修改用戶信息
	 */
	@RequestMapping("/update")
	@ResponseBody
	public ReturnJsonBean update(String user_id, String username, String header, Integer gender, String birthday) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			User user = userService.get(user_id);
			UserModel model = new UserModel();
			if (username == null || "".equals(username.trim())) {
				model.setUsername(user.getUsername());
			} else {
				model.setUsername(username);
			}
			if (header == null || "".equals(header.trim())) {
				model.setHeader(user.getHeader());
			} else {
				model.setHeader(header);
			}
			if (birthday == null || "".equals(birthday.trim())) {
				model.setBirthday(user.getBirthday());
			} else {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				model.setBirthday(new Timestamp(sdf.parse(birthday).getTime()));
			}
			if (gender == null || gender == -1) {
				model.setGender(user.getGender());
			} else {
				model.setGender(gender);
			}
			model.setUserId(user_id);
			userService.updateUser(model);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "info()", e);
		}
		return rb;
	}

	/**
	 * 江湖口号
	 */
	@RequestMapping("/declare")
	@ResponseBody
	public ReturnJsonBean declare(String user_id, String declaration) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			userService.declare(user_id, declaration);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "info()", e);
		}
		return rb;
	}

	/**
	 * 生成支付订单
	 */
	@RequestMapping("/build/pay/order")
	@ResponseBody
	public ReturnJsonBean build_pay_order(String user_id, String order_id, Integer coupon_type, String coupon_id,
			Integer pay_type, Integer pay_way, HttpServletRequest request) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			PayOrder order = userService.addPayOrder(user_id, order_id, coupon_type, coupon_id, pay_type, pay_way);

			Map<String, Object> payOrderMap = new HashMap<String, Object>();
			int payType = (Integer) order.getPay_type();
			if (payType == 1 || payType == 2) {
				// 支付宝回调地址 (域名后续加入配置中)
				payOrderMap.put("payOrder", order);
				payOrderMap.put("prepay_map", null);
				payOrderMap.put("notify_url", "http://www.yihusong.com/hsconsumer/user/alipay/notify");
			} else if (payType == 3 || payType == 4) {
				// 微信回调地址（域名后续加入配置中）

				String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
				String entity = genProductArgs(order.getPay_order_no());
				byte[] buf = Util.httpPost(url, entity);

				String content = new String(buf);

				SAXBuilder builder = new SAXBuilder();
				StringReader read = new StringReader(content);
				InputSource source = new InputSource(read);
				Document document = null;
				try {
					document = builder.build(source);
				} catch (Exception e) {
					returnFail(rb, ReturnCodeAndMsg.GET_PREPAYID_FAIL, ReturnCodeAndMsg.GET_PREPAYID_FAIL_MSG);
					return rb;
				}
				Element root = document.getRootElement();

				Map<String, String> prepay_map = new HashMap<String, String>();
				String prepay_id = root.getChildText("prepay_id");
				String appid = root.getChildText("appid");
				String mch_id = root.getChildText("mch_id");
				String nonce_str = root.getChildText("nonce_str");
				String trade_type = root.getChildText("trade_type");
				long timestame = genTimeStamp();
				prepay_map.put("prepay_id", prepay_id);
				prepay_map.put("appid", appid);
				prepay_map.put("mch_id", mch_id);
				prepay_map.put("nonce_str", nonce_str);
				prepay_map.put("partnerid", Constants.API_KEY);
				prepay_map.put("timestamp", timestame + "");
				prepay_map.put("packages", "Sign=WXPay");
				List<NameValuePair> signParams = new LinkedList<NameValuePair>();
				signParams.add(new BasicNameValuePair("appid", appid));
				signParams.add(new BasicNameValuePair("noncestr", nonce_str));
				signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
				signParams.add(new BasicNameValuePair("partnerid", Constants.API_KEY));
				signParams.add(new BasicNameValuePair("prepayid", prepay_id));
				signParams.add(new BasicNameValuePair("timestamp", timestame + ""));
				prepay_map.put("sign", genAppSign(signParams));
				prepay_map.put("trade_type", trade_type);
				payOrderMap.put("payOrder", order);
				payOrderMap.put("prepay_map", prepay_map);
				payOrderMap.put("notify_url", "http://www.yihusong.com/hsconsumer/user/weixin/notify");
			}
			rb.setData(payOrderMap);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "build_pay_order()", e);
		}
		return rb;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map parseXmlToList2(String xml) {
		Map retMap = new HashMap();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			org.jdom.Document doc = sb.build(source);
			Element root = (Element) doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}

	/**
	 * 微信回调
	 */
	@SuppressWarnings("null")
	@RequestMapping("/weixin/notify")
	@ResponseBody
	public void weixin_notify(HttpServletRequest request, HttpServletResponse response) {

		String inputLine;
		String notityXml = "";
		String resXml = "";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();

			Map m = parseXmlToList2(notityXml);
			Map<String, String> map = new TreeMap<String, String>();

			map.put("appid", m.get("appid").toString());
			map.put("mch_id", m.get("mch_id").toString());
			map.put("nonce_str", m.get("nonce_str").toString());
			map.put("sign", m.get("sign").toString());
			map.put("result_code", m.get("result_code").toString());
			map.put("openid", m.get("openid").toString());
			map.put("is_subscribe", m.get("is_subscribe").toString());
			map.put("trade_type", m.get("trade_type").toString());
			map.put("bank_type", m.get("bank_type").toString());
			map.put("total_fee", m.get("total_fee").toString());
			map.put("cash_fee", m.get("cash_fee").toString());
			map.put("transaction_id", m.get("transaction_id").toString());
			map.put("out_trade_no", m.get("out_trade_no").toString());
			map.put("time_end", m.get("time_end").toString());
			map.put("return_code", m.get("return_code").toString());
			if (m.get("device_info") != null) {
				map.put("device_info", m.get("device_info").toString());
			}
			if (m.get("err_code") != null) {
				map.put("err_code", m.get("err_code").toString());
			}
			if (m.get("err_code_des") != null) {
				map.put("err_code_des", m.get("err_code_des").toString());
			}
			if (m.get("fee_type") != null) {
				map.put("fee_type", m.get("fee_type").toString());
			}
			if (m.get("cash_fee_type") != null) {
				map.put("cash_fee_type", m.get("cash_fee_type").toString());
			}
			if (m.get("coupon_fee") != null) {
				map.put("coupon_fee", m.get("coupon_fee").toString());
			}
			if (m.get("coupon_count") != null) {
				map.put("coupon_count", m.get("coupon_count").toString());
			}
			if (m.get("attach") != null) {
				map.put("attach", m.get("attach").toString());
			}
			if (m.get("return_msg") != null) {
				map.put("return_msg", m.get("return_msg").toString());
			}

			StringBuilder sb = new StringBuilder();

			Set es = map.entrySet();
			Iterator it = es.iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				String k = (String) entry.getKey();
				String v = (String) entry.getValue();
				if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
					sb.append(k + "=" + v + "&");
				}
			}
			sb.append("key=");
			sb.append(Constants.API_KEY);
			String enc = TenpayUtil.getCharacterEncoding(request, response);
			String sign = MD5Util.MD5Encode(sb.toString(), enc).toUpperCase();
			String tenpaySign = m.get("sign").toString();
			if (tenpaySign.equals(sign)) {
				WxPayResult wpr = new WxPayResult();
				wpr.setAppid(m.get("appid").toString());
				wpr.setBankType(m.get("bank_type").toString());
				wpr.setCashFee(m.get("cash_fee").toString());
				wpr.setIsSubscribe(m.get("is_subscribe").toString());
				wpr.setMchId(m.get("mch_id").toString());
				wpr.setNonceStr(m.get("nonce_str").toString());
				wpr.setOpenid(m.get("openid").toString());
				wpr.setOutTradeNo(m.get("out_trade_no").toString());
				wpr.setResultCode(m.get("result_code").toString());
				wpr.setReturnCode(m.get("return_code").toString());
				wpr.setSign(m.get("sign").toString());
				wpr.setTimeEnd(m.get("time_end").toString());
				wpr.setTotalFee(m.get("total_fee").toString());
				wpr.setTradeType(m.get("trade_type").toString());
				wpr.setTransactionId(m.get("transaction_id").toString());
				if (m.get("device_info") != null) {
					wpr.setDeviceInfo(m.get("device_info").toString());
				}
				if (m.get("fee_type") != null) {
					wpr.setFeeType(m.get("fee_type").toString());
				}

				if ("SUCCESS".equals(wpr.getResultCode())) {
					try {
						userService.notifyWeixinUser(wpr);
						resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
								+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
					} catch (Exception e) {
						resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
						e.printStackTrace();
					}
					// 支付成功
				} else {
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} else {
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 支付宝回调
	 */
	@SuppressWarnings("null")
	@RequestMapping("/alipay/notify")
	@ResponseBody
	public void alipay_notify(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			e1.printStackTrace();
			out.println("fail");
		}
		String result = "fail";
		try {
			result = userService.notifyAlipayUser(request);
		} catch (Exception e) {
			e.printStackTrace();
			out.println("fail");
		}
		if ("success".equals(result)) {
			out.println("success");
		} else {
			out.println("fail");
		}
	}

	/**
	 * 充值金额列表
	 */
	@RequestMapping("/recharge/list")
	@ResponseBody
	public ReturnJsonBean recharge_list() {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			List<RechargeList> list = userService.getRechargeLists();
			rb.setData(list);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "recharge_list()", e);
		}
		return rb;
	}

	/**
	 * 生成签名
	 */

	public static String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return packageSign;
	}

	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}

	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<" + params.get(i).getName() + ">");

			sb.append(params.get(i).getValue());
			sb.append("</" + params.get(i).getName() + ">");
		}
		sb.append("</xml>");

		return sb.toString();
	}

	private String genProductArgs(String out_trade_no) throws Exception {
		PayOrder order = userService.getPayOrderByPayOrderNo(out_trade_no);
		BigDecimal amount = (BigDecimal) order.getAmount();
		Integer payWay = (Integer) order.getPay_way();

		try {
			String nonceStr = genNonceStr();

			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
			if (payWay == 1) {// 微信充值
				packageParams.add(new BasicNameValuePair("body", "呼送充值__" + out_trade_no));
			} else {// 微信支付
				packageParams.add(new BasicNameValuePair("body", "呼送支付__" + out_trade_no));
			}
			packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams
					.add(new BasicNameValuePair("notify_url", "http://www.yihusong.com/hsconsumer/user/weixin/notify"));
			packageParams.add(new BasicNameValuePair("out_trade_no", out_trade_no));
			packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
			packageParams.add(new BasicNameValuePair("total_fee", (int) (amount.doubleValue() * 100) + ""));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));

			String xmlstring = toXml(packageParams);

			return xmlstring;

		} catch (Exception e) {
			return null;
		}
	}

	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}

	// /**
	// * 微信支付生成prepayId
	// *
	// * @param amount
	// * @param payType
	// * @param userId
	// * @return
	// */
	// @RequestMapping("/build/prepayid")
	// @ResponseBody
	// public ReturnJsonBean build_prepayid(HttpServletRequest
	// request,HttpServletResponse response,String payOrderNo) {
	//
	// ReturnJsonBean rb = new ReturnJsonBean();
	// try {
	// String url =
	// String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
	// String entity = genProductArgs(payOrderNo,request);
	//
	//
	// byte[] buf = Util.httpPost(url, entity);
	//
	// String content = new String(buf);
	//
	// SAXBuilder builder = new SAXBuilder();
	// StringReader read = new StringReader(content);
	// InputSource source = new InputSource(read);
	// Document document = null;
	// try {
	// document = builder.build(source);
	// } catch (Exception e) {
	// returnFail(rb, ReturnCodeAndMsg.GET_PREPAYID_FAIL,
	// ReturnCodeAndMsg.GET_PREPAYID_FAIL_MSG);
	// return rb;
	// }
	// Element root = document.getRootElement();
	// String prepay_id=root.getChildText("prepay_id");
	//
	// Map<String,String> prepayMap=new HashMap<String, String>();
	// prepayMap.put("prepay_id", prepay_id);
	// rb.setData(prepayMap);
	// returnSuccess(rb);
	// } catch (Exception e) {
	// e.printStackTrace();
	// saveException(jincongmin.getName(), "UserController", "build_prepayid()",
	// e);
	// }
	// return rb;
	// }

	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return appSign;
	}

	/**
	 * 用户确认订单信息后点击确认支付接口
	 * 
	 * @param payOrderNo
	 *            唯一订单号
	 * @return 订单详细信息
	 */
	@RequestMapping("/notify/url")
	@ResponseBody
	public ReturnJsonBean notify_url(String payOrderNo, HttpServletRequest request) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			PayOrder order = userService.getPayOrderByPayOrderNo(payOrderNo);
			Map<String, Object> payOrderMap = new HashMap<String, Object>();
			int payType = (Integer) order.getPay_type();
			if (payType == 1 || payType == 2) {
				// 支付宝回调地址 (域名后续加入配置中)
				payOrderMap.put("payOrder", order);
				payOrderMap.put("prepay_map", null);
				payOrderMap.put("notify_url", "http://www.yihusong.com/hsconsumer/user/alipay/notify");
			} else if (payType == 3 || payType == 4) {
				// 微信回调地址（域名后续加入配置中）

				String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
				String entity = genProductArgs(payOrderNo);
				byte[] buf = Util.httpPost(url, entity);

				String content = new String(buf);

				SAXBuilder builder = new SAXBuilder();
				StringReader read = new StringReader(content);
				InputSource source = new InputSource(read);
				Document document = null;
				try {
					document = builder.build(source);
				} catch (Exception e) {
					returnFail(rb, ReturnCodeAndMsg.GET_PREPAYID_FAIL, ReturnCodeAndMsg.GET_PREPAYID_FAIL_MSG);
					return rb;
				}
				Element root = document.getRootElement();

				Map<String, String> prepay_map = new HashMap<String, String>();
				String prepay_id = root.getChildText("prepay_id");
				String appid = root.getChildText("appid");
				String mch_id = root.getChildText("mch_id");
				String nonce_str = root.getChildText("nonce_str");
				String trade_type = root.getChildText("trade_type");
				long timestame = genTimeStamp();
				prepay_map.put("prepay_id", prepay_id);
				prepay_map.put("appid", appid);
				prepay_map.put("mch_id", mch_id);
				prepay_map.put("nonce_str", nonce_str);
				prepay_map.put("partnerid", Constants.API_KEY);
				prepay_map.put("timestamp", timestame + "");
				prepay_map.put("packages", "Sign=WXPay");
				List<NameValuePair> signParams = new LinkedList<NameValuePair>();
				signParams.add(new BasicNameValuePair("appid", appid));
				signParams.add(new BasicNameValuePair("noncestr", nonce_str));
				signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
				signParams.add(new BasicNameValuePair("partnerid", Constants.API_KEY));
				signParams.add(new BasicNameValuePair("prepayid", prepay_id));
				signParams.add(new BasicNameValuePair("timestamp", timestame + ""));
				prepay_map.put("sign", genAppSign(signParams));
				prepay_map.put("trade_type", trade_type);
				payOrderMap.put("payOrder", order);
				payOrderMap.put("prepay_map", prepay_map);
				payOrderMap.put("notify_url", "http://www.yihusong.com/hsconsumer/user/weixin/notify");
			}
			rb.setData(payOrderMap);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "notify_url()", e);
		}
		return rb;
	}

	/**
	 * 提现订单
	 */
	@RequestMapping("/build/withdraw/order")
	@ResponseBody
	public ReturnJsonBean build_withdraw_order(String user_id, String bindaccountid, double amount, String password) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			UserWalletBean wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			if (wallet == null) {
				userService.addUserWallet(user_id);
				wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			}

			if (!password.equals(wallet.getPay_password())) {
				returnFail(rb, ReturnCodeAndMsg.WALLET_PASSWORD_ILLEGAL, ReturnCodeAndMsg.WALLET_PASSWORD_ILLEGAL_MSG);
				return rb;
			}
			double purchaseBalance = wallet.getPurchase_amount().doubleValue();
			double tipBalance = wallet.getTip_amount().doubleValue();
			double total = purchaseBalance;
			if (tipBalance <= 5) {
				total += 0;
			} else if (tipBalance < 50) {
				total += (tipBalance - 5);
			} else {
				total += tipBalance * 0.9;
			}

			if (amount <= 0 || amount > total || total <= 0) {
				returnFail(rb, ReturnCodeAndMsg.WALLET_WITHDRAW_IS_LACK, ReturnCodeAndMsg.WALLET_WITHDRAW_IS_LACK_MSG);
				return rb;
			}
			AccountBindBean bind = userService.getAccountBind(bindaccountid);

			WithdrawOrderBean withdraw = new WithdrawOrderBean();
			withdraw.setId(UUIDUtil.getUUID());
			withdraw.setCreate_time(new Timestamp(System.currentTimeMillis()));
			withdraw.setReal_name(bind.getReal_name());
			withdraw.setService_amount(BigDecimal.ZERO);
			withdraw.setStatus(1);
			withdraw.setUser_id(user_id);
			withdraw.setWithdraw_account_no(bind.getAccount_no());
			withdraw.setWithdraw_amount(BigDecimal.valueOf(amount));
			withdraw.setWithdraw_desc("");
			withdraw.setWithdraw_order_no(PayOrderNoUtil.getPayOrderNo());
			withdraw.setWithdraw_type(bind.getAccount_type());
			userService.addWithdrawOrder(withdraw);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "build_withdraw_order()", e);
		}
		return rb;
	}

	/**
	 * 账单
	 */
	@RequestMapping("/bills")
	@ResponseBody
	public ReturnJsonBean bills(String user_id, Long lastDate, Long lastrowid) {
		ReturnJsonBean rb = new ReturnJsonBean();
		String lastDateStr = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (lastDate == null || lastDate == 0) {
			lastDateStr = sdf.format(new Date());
		} else {
			lastDateStr = sdf.format(lastDate);
		}
		try {
			List<WalletBean> bills = userService.getBills(user_id, lastDateStr, lastrowid);
			rb.setData(bills);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "bills()", e);
		}
		return rb;
	}

	/**
	 * 根据类型查询账单 1.代购，2.小费 3.提现 4.全部
	 */
	@RequestMapping("/bills/by/type")
	@ResponseBody
	public ReturnJsonBean bills_by_type(String user_id, Long lastDate, Long lastrowid, int type) {
		ReturnJsonBean rb = new ReturnJsonBean();
		String lastDateStr = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (lastDate == null || lastDate == 0) {
			lastDateStr = sdf.format(new Date());
		} else {
			lastDateStr = sdf.format(lastDate);
		}
		try {
			List<BillBean> bills = userService.getBillsByType(user_id, lastDateStr, lastrowid, type);
			BillDetailBean detail = new BillDetailBean();
			detail.setBills(bills);
			UserWalletBean wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			if (wallet == null) {
				userService.addUserWallet(user_id);
				wallet = userService.getUsefullUserWalletBeanByUserId(user_id);
			}
			if (type == 1) {
				detail.setAvailableAmount(wallet.getPurchase_amount());
				detail.setHistoryAmount(userService.getPurchaseSumAmount(user_id));

			} else if (type == 2) {
				detail.setAvailableAmount(wallet.getTip_amount());
				detail.setHistoryAmount(userService.getTipSumAmount(user_id));

			} else if (type == 3) {

				detail.setAvailableAmount(wallet.getFrozen_amount());
				detail.setHistoryAmount(userService.getWithdrawSumAmount(user_id));
			} else if (type == 4) {

				detail.setAvailableAmount(BigDecimal.ZERO);
				detail.setHistoryAmount(BigDecimal.ZERO);
			}
			rb.setData(detail);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "bills_by_type()", e);
		}
		return rb;
	}

	/**
	 * 呼送热线
	 */
	@RequestMapping("/hotline")
	@ResponseBody
	public ReturnJsonBean hotline() {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("hotline", "4006628232");
			rb.setData(map);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "hotline()", e);
		}
		return rb;
	}

	/**
	 * 呼送注册协议
	 */
	@RequestMapping("/protocol")
	@ResponseBody
	public ReturnJsonBean protocol() {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("protocol",
					"本服务条款是您与呼送信息服务平台（包含呼送网站、呼送手机终端软件）的所有者-----“南京呼送电子科技有限公司”（南京呼送电子科技有限公司及其关联公司、呼送信息服务平台在协议中统称为“呼送”，通过呼送信息服务平台为您提供服务）之间就呼送提供的信息服务等相关事宜所订立的合约或合同。 </br>"
							+ "请您仔细阅读本条款，您勾选“我已了解并接受《注册服务条款》”并点击【立即注册】按钮注册成功后成为呼送的正式会员，本服务条款即构成了对双方具有法律约束力的文件。</br>"
							+ "第1条 定义</br>"
							+ "呼送信息服务平台，为提供及维护信息发布的服务平台。其为平台注册用户（信息发布方和接收方）提供信息中介和管理服务，并设计、开发信息服务产品，形成参考价格。</br>"
							+ "平台注册用户是指通过呼送信息服务平台完成全部注册程序后，使用呼送信息服务平台服务的用户。</br>"
							+ "自由经纪人，是指申请注册并经呼送审核通过后，通过呼送信息服务平台自主选择接受任务信息、完成任务事项，并在事项完成后获得信息发布方给付的相应报酬的平台注册用户。 </br>"
							+ "信息发布方，是指在呼送信息服务平台上创建、发布任务事项信息的平台注册用户。 </br>"
							+ "信息接受方，是指在呼送信息服务平台上勾选、接受已发布的任务事项信息的自由经纪人。</br>" + "第2条 服务条款的确认和接受</br>");
			rb.setData(map);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "protocol()", e);
		}
		return rb;
	}

	/**
	 * 意见反馈
	 */
	@RequestMapping("/feedback")
	@ResponseBody
	public ReturnJsonBean feedback(String user_id, String text, String version, String system) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			Feedback feedback = new Feedback();
			feedback.setCreate_date(new Timestamp(System.currentTimeMillis()));
			feedback.setSystem(system);
			feedback.setText(text);
			feedback.setUser_id(user_id);
			feedback.setVersion(version);
			userService.addFeedback(feedback);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "feedback()", e);
		}
		return rb;
	}

	/**
	 * 推荐有奖
	 */
	@RequestMapping("/invite")
	@ResponseBody
	public ReturnJsonBean invite(String user_id) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			BigDecimal inviteAmount = userService.getInviteAmount(user_id);
			User user = userService.get(user_id);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("inviteCode", user.getTelephone());
			map.put("inviteAmount", inviteAmount == null ? BigDecimal.ZERO : inviteAmount);
			rb.setData(map);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "invite()", e);
		}
		return rb;
	}

	/**
	 * 推送通知
	 */
	@RequestMapping("/advice")
	@ResponseBody
	public ReturnJsonBean advice(String user_id, int type) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			String tag = "broker";
			if (type == 1) {
				tag = "broker";
			} else {
				tag = "";
			}
			userService.updateUserTag(user_id, tag);
			returnSuccess(rb);
		} catch (Exception e) {
			e.printStackTrace();
			saveException(jincongmin.getName(), "UserController", "advice()", e);
		}
		return rb;
	}

	private String time(String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(new Date());
	}

	@RequestMapping("/gen/beforeTw")
	@ResponseBody
	public String genBatchWithdrawOrderBefore12() {
		final String pattern = "yyyy-MM-dd 12:00:00";
		new Thread(new Runnable() {
			public void run() {
				// logger.info("生成批量付款订单入参，pattern：{}",pattern);
				String time = time(pattern);
				int count = userService.queryWithdrawOrderCount(time);
				int n = (count / UserService.BATCH_NUM) + 1;// 每100笔生成一笔批量付款订单
				for (int i = 0; i < n; i++) {
					String batchOrderNo = time("yyyyMMddHHmmss") + i;
					try {
						userService.genBatchWithdrawOrder(batchOrderNo, pattern);
					} catch (Exception e) {
						n++;
						continue;
					}
				}
				// logger.info("生成批量付款订单岀参，count：{}",count);
			}
		}).start();

		return "success";
	}

	@RequestMapping("/gen/afterTw")
	@ResponseBody
	public String genBatchWithdrawOrderAfter12() {
		final String pattern = "yyyy-MM-dd 00:00:00";
		new Thread(new Runnable() {
			public void run() {
				// logger.info("生成批量付款订单入参，pattern：{}",pattern);
				String time = time(pattern);
				int count = userService.queryWithdrawOrderCount(time);
				int n = (count / UserService.BATCH_NUM) + 1;// 每100笔生成一笔批量付款订单
				for (int i = 0; i < n; i++) {
					String batchOrderNo = time("yyyyMMddHHmmss") + i;
					try {
						userService.genBatchWithdrawOrder(batchOrderNo, pattern);
					} catch (Exception e) {
						n++;
						continue;
					}
				}
				// logger.info("生成批量付款订单岀参，count：{}",count);
			}
		}).start();
		return "success";
	}

}
